import '../services/api_service.dart';
import '../services/websocket_service_rust.dart';
import '../services/image_cache_service.dart';
import '../repositories/auth_repository.dart';
import '../repositories/friend_repository.dart';
import '../repositories/chat_repository.dart';
import '../../shared/storage/storage_service.dart';
import '../../shared/providers/bottom_nav_provider.dart';
import '../viewmodels/auth_viewmodel.dart';
import '../viewmodels/contacts_viewmodel.dart';
import '../viewmodels/home_viewmodel.dart';

class ServiceLocator {
  static final ServiceLocator _instance = ServiceLocator._internal();
  factory ServiceLocator() => _instance;
  ServiceLocator._internal();

  late final StorageService _storageService;
  late final ApiService _apiService;
  late final WebSocketServiceRust _webSocketService;
  late final ImageCacheService _imageCacheService;
  late final AuthRepository _authRepository;
  late final FriendRepository _friendRepository;
  late final ChatRepository _chatRepository;
  late final AuthViewModel _authViewModel;
  late final ContactsViewModel _contactsViewModel;
  late final HomeViewModel _homeViewModel;
  late final BottomNavProvider _bottomNavProvider;

  Future<void> init() async {
    // Initialize storage
    await StorageService.init();
    _storageService = StorageService();

    // Initialize services
    _apiService = ApiService(_storageService);
    _webSocketService = WebSocketServiceRust(_storageService);
    _imageCacheService = ImageCacheService();
    await _imageCacheService.init();

    // Initialize repositories
    _authRepository = AuthRepository(_apiService, _storageService);
    _friendRepository = FriendRepository(_apiService);
    _chatRepository = ChatRepository(_apiService);

    // Initialize view models
    _authViewModel = AuthViewModel(_authRepository);
    // 设置 WebSocket 服务到 AuthViewModel，用于退出时断开连接
    _authViewModel.setWebSocketService(_webSocketService);
    _contactsViewModel = ContactsViewModel(_friendRepository);
    _homeViewModel = HomeViewModel(_friendRepository, _chatRepository);

    // Initialize providers
    _bottomNavProvider = BottomNavProvider();
  }

  StorageService get storageService => _storageService;
  ApiService get apiService => _apiService;
  WebSocketServiceRust get webSocketService => _webSocketService;
  ImageCacheService get imageCacheService => _imageCacheService;
  AuthRepository get authRepository => _authRepository;
  FriendRepository get friendRepository => _friendRepository;
  ChatRepository get chatRepository => _chatRepository;
  AuthViewModel get authViewModel => _authViewModel;
  ContactsViewModel get contactsViewModel => _contactsViewModel;
  HomeViewModel get homeViewModel => _homeViewModel;
  BottomNavProvider get bottomNavProvider => _bottomNavProvider;
}

